package org.systm.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.global.AjaxResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class DefaultAuthenticationFailHandler implements AuthenticationFailureHandler {

    ObjectMapper objectMapper;

    public DefaultAuthenticationFailHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        AjaxResult ajaxResult = AjaxResult.builder().code(401).msg("身份认证失败").build();
        response.getWriter().write(objectMapper.writeValueAsString(ajaxResult));
    }
}
